import 'es6-promise/auto';
import { createStore } from 'vuex';
import UserStore from '@zeesuu/login/store/user';
import { defineAsyncComponent } from 'vue';

export const ROUTE_PREFIX = new RegExp(/\/\$dis/);
// IMPORTANT: 在Vite里面 懒加载这样玩
// https://github.com/vitejs/vite/issues/745#issuecomment-759075943
const modules = import.meta.glob('../views/*.vue');

/**
 * 路由生成器
 * @param {*} route
 */
const routeGenerator = (route) => {
  const BasicConfig = {
    path: route.path.replace(ROUTE_PREFIX, ''),
    name: route.name,
    meta: {
      title: route.title,
    },
  };

  return route.component
    ? {
        ...BasicConfig,
        component: modules[`../views${route.component.replace(ROUTE_PREFIX, '')}.vue`],
      }
    : BasicConfig;
};

const {
  state: userState,
  getters: userGetters,
  mutations: userMutations,
  actions: userActions,
} = UserStore({ token: '' });

const store = createStore({
  state() {
    return {
      menu: [],
      permission: [],
      asyncRoute: [],
      ...userState,
    };
  },
  getters: {
    $menu: (state) => state.menu,
    $permission: (state) => state.permission,
    $asyncRoute: (state) => state.asyncRoute,
    ...userGetters,
  },
  mutations: {
    SET_MENUS(state, payload) {
      state.menu = payload;
    },
    SET_PERMISSION(state, payload) {
      state.permission = payload;
    },
    SET_ASYNCROUTE(state, payload) {
      state.asyncRoute = payload;
    },
    ...userMutations,
  },
  actions: {
    $setMenus({ commit }, _) {
      // 过滤特殊标记的路由
      const payload = _.filter((p) => p.path.match(ROUTE_PREFIX));

      commit('SET_MENUS', payload);

      // 构建路由
      let routes = [];

      payload.map((p) => {
        // 如果
        if (p.type === 1) {
          routes.concat(routeGenerator(p));
        }

        routes.push({
          ...routeGenerator(p),
        });

        if (Array.isArray(p.children)) {
          routes = routes.concat(
            p.children
              .filter((pChild) => pChild.type === 1)
              .map((pChild) => routeGenerator(pChild)),
          );
        }
      });

      commit('SET_ASYNCROUTE', [...routes]);
    },
    $setPermission({ commit }, payload) {
      commit('SET_PERMISSION', payload);
    },
    ...userActions,
  },
});

export default store;
